package org.microservice.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import com.xiaoleilu.hutool.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.microservice.common.config.FilterIgnorePropertiesConfig;
import org.microservice.gateway.service.LogSendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;

/**
 * @author lengleng
 * @date 2017/11/16
 * 网关日志拦截器
 */
@Slf4j
@Component
public class LoggerFilter extends ZuulFilter {

    @Autowired
    private LogSendService logSendService;

    @Autowired
    private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;


    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext requestContext = RequestContext.getCurrentContext();
        List<String> noLogs = filterIgnorePropertiesConfig.getNoLog();
        HttpServletRequest request = requestContext.getRequest();


        String path = URLUtil.getPath(request.getRequestURI());

        for (String s:
             noLogs) {
            if(path.matches(s)){
                return null;
            }
        }
        logSendService.send(requestContext);

        return null;
    }
}
